package com.xbongbong.config;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.parent.interfaces.BusinessConditionService;
import com.xbongbong.parent.interfaces.BusinessPermissionService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 权限和条件的封装方法
 * @author 吴峰
 * @date 2022/10/25 10:33
 */
@Component
public class BusinessConditionConfig implements ApplicationContextAware {

    private Map<String, BusinessPermissionService> businessPermissionMap;
    private Map<String, BusinessConditionService> businessConditionMap;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        businessPermissionMap = applicationContext.getBeansOfType(BusinessPermissionService.class);
        businessConditionMap = applicationContext.getBeansOfType(BusinessConditionService.class);
    }

    /**
     * 权限相关
     * @return
     */
    @Bean("businessPermissionMap")
    public Map<Integer, BusinessPermissionService> businessPermissionServiceMap() {
        Map<Integer, BusinessPermissionService> resultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.isNull(businessPermissionMap)) {
            return resultMap;
        }
        this.businessPermissionMap.forEach((key, item)->{
            item.businessType().forEach(type->resultMap.put(Integer.valueOf(type.toString()), item));
        });
        return resultMap;
    }

    /**
     * 条件相关
     * @return
     */
    @Bean("businessConditionMap")
    public Map<Integer, BusinessConditionService> businessConditionServiceMap() {
        Map<Integer, BusinessConditionService> resultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.isNull(businessConditionMap)) {
            return resultMap;
        }
        this.businessConditionMap.forEach((key, item)->{
            item.businessType().forEach(type->resultMap.put(Integer.valueOf(type.toString()), item));
        });
        return resultMap;
    }
}
